package io.oschina.binv.kapp.framework


import android.app.Activity
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.support.v4.app.Fragment
import android.support.v7.widget.AppCompatCheckBox
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.view.*
import android.widget.*
import com.yalantis.ucrop.UCrop
import com.yalantis.ucrop.model.AspectRatio
import io.oschina.binv.kapp.R
import io.oschina.binv.kapp.framework.extend.*
import io.oschina.binv.kapp.framework.utils.MediaScanner
import io.oschina.binv.kapp.framework.widget.*
import io.oschina.binv.kapp.framework.widget.MEDIA_IMAGE
import io.oschina.binv.kapp.framework.widget.MEDIA_VIDEO
import io.oschina.binv.kapp.framework.widget.MediaItem
import io.oschina.binv.kapp.framework.widget.MediaPicker
import io.oschina.binv.kapp.framework.widget.video.JCVideoPlayer
import io.oschina.binv.kapp.framework.widget.video.JCVideoPlayerStandard
import java.io.File


/**
 * A simple [Fragment] subclass.
 */
class ImagePreviewFragment : BaseFragment() {
    override fun setContentView(inflater: LayoutInflater, container: ViewGroup?): View {
        return inflater.inflate(R.layout.fragment_image_preview, container, false)
    }
    val backIv by lazy {
        findViewById<ImageView>(R.id.btn_back)
    }
    val desTv by lazy {
        findViewById<TextView>(R.id.tv_des)
    }
    val okBtn by lazy {
        findViewById<Button>(R.id.btn_ok)
    }

    val bigRv by lazy {
        findViewById<RecyclerView>(R.id.rv_big)
    }

    val smallRv by lazy {
        findViewById<RecyclerView>(R.id.rv_small)
    }
    val smallPopRl by lazy {
        findViewById<RelativeLayout>(R.id.rl_small_pop)
    }
    val editTv by lazy {
        findViewById<TextView>(R.id.tv_edit)
    }

    val checkFl by lazy {
        findViewById<FrameLayout>(R.id.fl_check)
    }
    val checkAccb by lazy {
        findViewById<AppCompatCheckBox>(R.id.accb_check)
    }

    companion object {
        val PAYLOAD_SELECT_ITEMS="PAYLOAD_SELECT_ITEMS"
        val PAYLOAD_SELECT_LIMIT="PAYLOAD_SELECT_LIMIT"
        val PAYLOAD_SELECT_FOLDER_ITEMS="PAYLOAD_SELECT_FOLDER_ITEMS"
        val PAYLOAD_SELECT_FOLDER_PREVIEW_POSITION="PAYLOAD_SELECT_FOLDER_PREVIEW_POSITION"
        data class  PreviewSelectItemsEvent(val selectItems:ArrayList<MediaItem>)
    }
    var payloadSelectItems= arrayListOf<MediaItem>()
    var payloadSelectLimit=1
    var payloadSelectFolderItems=arrayListOf<MediaItem>()
    var selectFolderPreviewPosition=0
    override fun initViewsAndLocalData(savedBundle: Bundle): (outBundle: Bundle) -> Unit {
        try {
            payloadSelectItems=savedBundle.getParcelableArrayList<MediaItem>(PAYLOAD_SELECT_ITEMS)
        }catch (ex:Throwable){
            context.printOrReport(ex)
        }
        if(payloadSelectItems==null){
            payloadSelectItems= arrayListOf<MediaItem>()
        }
        payloadSelectLimit=savedBundle.getInt(PAYLOAD_SELECT_LIMIT,1)
        try {
            payloadSelectFolderItems=savedBundle.getParcelableArrayList<MediaItem>(PAYLOAD_SELECT_FOLDER_ITEMS)
        }catch (ex:Throwable){
            context.printOrReport(ex)
        }
        if(payloadSelectFolderItems==null){
            payloadSelectFolderItems= arrayListOf<MediaItem>()
        }
        selectFolderPreviewPosition=savedBundle.getInt(PAYLOAD_SELECT_FOLDER_PREVIEW_POSITION,0)

        //结束前发送结果
        beforeFinishRunAsync{
            RxBus.post(PreviewSelectItemsEvent(payloadSelectItems))
        }
        backIv.setOnClickListener{finish()}
        okBtn.setOnClickListener{_->
            val data=finishEventFor(MediaPickerFragment::class.java.canonicalName)
            Log.i(data.toString())
            //单选时,追加
            if (payloadSelectLimit==1 && payloadSelectItems.size==0 && payloadSelectFolderItems.size>0){
                payloadSelectItems.add(payloadSelectFolderItems[selectFolderPreviewPosition])
            }
            RxBus.post(data)
            RxBus.post(SelectItemsEvent(payloadSelectItems))
            finish()
        }
        updateOkBtn()
        smallRv.startSnap(LinearLayoutManager.HORIZONTAL).adapter=context.commonAdapter(R.layout.fragment_image_preview_small_item,payloadSelectItems) { holder, data, _ ->
            val samllIv=holder.getView<ImageView>( R.id.iv_samll)
            MediaPicker.instance.displayMedia(data,samllIv)
            val maskV= holder.getView<View>(R.id.v_samll_mask)

            if (data==payloadSelectFolderItems[selectFolderPreviewPosition]){
                maskV.visibility=View.VISIBLE
            }else{
                maskV.visibility=View.GONE
            }
            samllIv.setOnClickListener{
                _->
                val folderItemsPosition= payloadSelectFolderItems.indexOf(data)
                if(folderItemsPosition>=0){
                    //小图加减选中边框
                    val upIndex=payloadSelectItems.indexOf(payloadSelectFolderItems[selectFolderPreviewPosition])
                    selectFolderPreviewPosition=folderItemsPosition
                    desTv.text="${selectFolderPreviewPosition+1}/${payloadSelectFolderItems.size}"
                    bigRv.scrollToPosition(selectFolderPreviewPosition)
                    if(upIndex>=0){
                        smallRv.adapter.notifyItemChanged(upIndex)
                    }
                    maskV.visibility=View.VISIBLE
                    checkAccb.isChecked=true
                }
            }
        }
        bigRv.pagerSnap(selectFolderPreviewPosition) {
            targetPos->
            desTv.text = "${selectFolderPreviewPosition + 1}/${payloadSelectFolderItems.size}"
            val thisIndex = payloadSelectItems.indexOf(payloadSelectFolderItems[targetPos])
            checkAccb.isChecked = thisIndex >= 0
            if (selectFolderPreviewPosition != targetPos) {
                val upIndex = payloadSelectItems.indexOf(payloadSelectFolderItems[selectFolderPreviewPosition])
                selectFolderPreviewPosition = targetPos
                //小图加减选中边框
                if (upIndex >= 0) {
                    smallRv.adapter.notifyItemChanged(upIndex)
                }
                if (thisIndex >= 0) {
                    smallRv.adapter.notifyItemChanged(thisIndex)
                    smallRv.smoothScrollToPosition(thisIndex)
                }
            }
        }.adapter=context.commonAdapter(R.layout.fragment_image_preview_big_item,payloadSelectFolderItems) { holder, data, _ ->
            MediaPicker.instance.displayMedia(data,holder.getView<ImageView>( R.id.iv_big))
            if(data.mediaType==MEDIA_VIDEO){
                holder.getView<ImageView>( R.id.iv_mask).visibility=View.VISIBLE
            }else{
                holder.getView<ImageView>( R.id.iv_mask).visibility=View.GONE
            }
        }
        bigRv.itemClick {
            vh->
            var videoUrl:String = ""  //原路径
            var videoUrls:String = "" //压缩后的路径
            if(payloadSelectFolderItems[vh.adapterPosition].mediaType === MEDIA_VIDEO){
                videoUrl = payloadSelectFolderItems[vh.adapterPosition].originalPath
                videoUrls = payloadSelectFolderItems[vh.adapterPosition].originalPath
                Log.i("原路径：$videoUrl,压缩后的路径$videoUrls")
                JCVideoPlayerStandard.startFullscreen(context, JCVideoPlayerStandard::class.java, videoUrl, "")

            }
        }
        bigRv.scrollToPosition(selectFolderPreviewPosition)
        checkFl.setOnClickListener{
            _->
            if(checkAccb.isChecked){
                val removedPosition=payloadSelectItems.indexOf(payloadSelectFolderItems[selectFolderPreviewPosition])
                payloadSelectItems.remove(payloadSelectFolderItems[selectFolderPreviewPosition])
                //smallRv.adapter.notifyDataSetChanged()
                smallRv.adapter.notifyItemRemoved(removedPosition)
                checkAccb.isChecked=false
            }else{
                if(payloadSelectItems.size<payloadSelectLimit && !payloadSelectItems.contains(payloadSelectFolderItems[selectFolderPreviewPosition])){
                    payloadSelectItems.add(payloadSelectFolderItems[selectFolderPreviewPosition])
                    //smallRv.adapter.notifyDataSetChanged()
                    smallRv.adapter.notifyItemInserted(payloadSelectItems.count()-1)
                    smallRv.smoothScrollToPosition(payloadSelectItems.count()-1)
                    checkAccb.isChecked=true
                }
            }
            updateOkBtn()
        }

        editTv.setOnClickListener { _->
            if(payloadSelectFolderItems[selectFolderPreviewPosition].mediaType==MEDIA_IMAGE){
                payloadSelectFolderItems[selectFolderPreviewPosition].compressPath=MediaPicker.instance.storeDir.absolutePath+File.separator+"crop_"+payloadSelectFolderItems[selectFolderPreviewPosition].originalPath.substringAfterLast(File.separator)
                val sourceUri= Uri.fromFile(File(payloadSelectFolderItems[selectFolderPreviewPosition].originalPath));
                val destinationUri= Uri.fromFile(File(payloadSelectFolderItems[selectFolderPreviewPosition].compressPath))
                val options=UCrop.Options()
                options.setFreeStyleCropEnabled(true)
                options.setAspectRatioOptions(0, AspectRatio("1:1",1f,1f))
                //options.withMaxResultSize(800,800)
                val intent=UCrop.of(sourceUri, destinationUri)
                        .withOptions(options)
                        .getIntent(context);
                startActivityForResult(intent,UCrop.REQUEST_CROP)
            }
        }
        return {
            outBundle ->
            try {
                //外部,传递值,未变化的可不更新
                outBundle.putParcelableArrayList(PAYLOAD_SELECT_ITEMS, payloadSelectItems)
                outBundle.putInt(PAYLOAD_SELECT_FOLDER_PREVIEW_POSITION, selectFolderPreviewPosition)

            }catch (ex:Throwable){
                context.printOrReport(ex)
            }
        }
    }
    val mediaScanner by lazy {
        MediaScanner(context)
    }
    override fun onDestroy() {
        super.onDestroy()
        mediaScanner.unScanFile()
    }


    override fun onPause() {
        super.onPause()
        JCVideoPlayer.releaseAllVideos()
    }


    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        when (item.itemId) {
            android.R.id.home -> finish()
        }
        return super.onOptionsItemSelected(item)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == Activity.RESULT_OK && requestCode == UCrop.REQUEST_CROP) {
            //val resultUri = UCrop.getOutput(data)
            val item=payloadSelectFolderItems[selectFolderPreviewPosition]
            if (item.compressPath.isNotEmpty() && File(item.compressPath).exists()){
                //替换原有的图片,然后再选中
                payloadSelectFolderItems.removeAt(selectFolderPreviewPosition)
                payloadSelectFolderItems.add(selectFolderPreviewPosition, MediaItem(item.compressPath,File(item.compressPath).length(),item.width ,item.height,item.addTime,item.mediaType,item.longitude,item.latitude,context.imageOrientation(item.compressPath)))
                //本次不添加,所以不需回调,刷新MediaPickerFragment
                mediaScanner.scanFile(item.compressPath)
                bigRv.adapter.notifyItemChanged(selectFolderPreviewPosition)
                val index = payloadSelectItems.indexOf(payloadSelectFolderItems[selectFolderPreviewPosition])
                if(index>=0){
                    smallRv.adapter.notifyItemChanged(index)
                }
            }
        } else if (resultCode == UCrop.RESULT_ERROR) {
            if(data!=null){
                val ex= UCrop.getError(data)
                if(ex!=null){
                    context.printOrReport(ex)
                }
            }
        }
    }


    override fun loadRemoteData() {

    }

    private fun updateOkBtn(){
        //预防视图已销毁
        isViewActiveRunNow {
            if(payloadSelectLimit==1){
                okBtn.apply {
                    text=resources.getString(R.string.mp_complete)
                    isEnabled=true
                }
                checkFl.visibility=View.GONE
            }else{
                //再次初始化完成按钮状态
                if(payloadSelectItems.size>0){
                    okBtn.apply {
                        text=String.format(resources.getString(R.string.mp_select_complete),payloadSelectItems.size, payloadSelectLimit)
                        isEnabled=true
                    }
                    smallPopRl.visibility=View.VISIBLE
                }else{
                    okBtn.apply {
                        text=resources.getString(R.string.mp_complete)
                        isEnabled=false
                    }
                    smallPopRl.visibility=View.GONE
                }
            }
        }
    }
}// Required empty public constructor
